<template>
  <div>
    <div style="height: 0px">
      <strong style="display: block; margin-top: 10px; text-align: center; font-size: 40px"
        >台风路径预测</strong
      >
    </div>
    <div className="hello">
      <div className="box">
        <div className="map">
          <div id="map" ref="map"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { useStore } from "vuex";
import { onMounted, onUnmounted, reactive, watch } from "vue";
import geoJson from "@/assets/yuegangao.json";
import { gettyphoonData } from "@/api/user/typhoon";
import regionStylesData from "@/assets/regionStyles.json";
import L from "leaflet";


export default {
  name: "typhoon",
  props: {
    totalData: {
      default: null,
    },
  },
  created() {
    //需要改
    this.$emit("changeTimeIndex", -1);
    this.$emit("changeIsSelect2", false);
    this.$emit("changeIsSelect3", false);
    this.$emit("changeIsTimeOperator", true);
  },
  setup(props) {
    const totalData = reactive(props.totalData);
    // console.log(totalData, "123456");
    watch(
      () => props.totalData,
      (newVal) => {
        console.log("totalData 发生了更改", newVal);
        totalData.value = newVal;
        params.year = newVal.getFullYear();
        params.month = newVal.getMonth() + 1;
        params.day = newVal.getDate();
        params.hour = newVal.getHours();
        params.minute = newVal.getMinutes();
        params.second = 0;
        console.log("new params:", params);
        updateMap();
      },
      { deep: true }
    );

    let mymap;
    let markerLayer = L.layerGroup();
    const store = useStore();
    let object = {
      user_id: store.state.userinfo.id,
      nums: 10,
    };
    const COLOR = ["red", "blue", "green", "orange", "purple"];
    let params = {
      year: 2023,
      month: 9,
      day: 1,
      hour: 0,
      minute: 0,
      second: 0,
    };

    onMounted(() => {
      initMap();
      updateMap();
    });
    onUnmounted(() => {
      if (mymap) {
        mymap.remove();
        mymap = null;
      }
    });

    async function initMap() {
      const guangdongCenter = [23.125178, 113.280637];
      mymap = L.map("map", { attributionControl: false }).setView(
        guangdongCenter,
        7
      );

      // 切换底图
      //矢量地图
      const tileLayer1 = L.tileLayer(
        "http://t{s}.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk={accessToken}",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          accessToken: "c9b286829db376e723c3dbed98c1b25e", // 替换为自己的访问令牌
        }
      );
      //影像地图
      const tileLayer2 = L.tileLayer(
        "http://t{s}.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk={accessToken}",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          accessToken: "c9b286829db376e723c3dbed98c1b25e", // 替换为自己的访问令牌
        }
      );
      //矢量地名
      const tileLayer3 = L.tileLayer(
        "http://t{s}.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk={accessToken}",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          accessToken: "c9b286829db376e723c3dbed98c1b25e", // 替换为自己的访问令牌
        }
      );
      //影像地名
      const tileLayer4 = L.tileLayer(
        "http://t{s}.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk={accessToken}",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          accessToken: "c9b286829db376e723c3dbed98c1b25e", // 替换为自己的访问令牌
        }
      );
      const baseMaps = {
        区划图: L.layerGroup([tileLayer1, tileLayer3]),
        地形图: L.layerGroup([tileLayer2, tileLayer4]),
      };
      tileLayer1.addTo(mymap);
      tileLayer3.addTo(mymap);
      L.control.layers(baseMaps).addTo(mymap);

      // 设置地图缩放范围
      mymap.setMinZoom(4);
      mymap.setMaxZoom(15);

      // 中国边界GeoJSON图层
      L.geoJSON(geoJson, {
        style: {
          fillColor: "none",
          fillOpacity: 0,
          color: "black",
          weight: 1,
          fillOpacity: 0.1,
        },
      }).addTo(mymap);

      function highlightFeature(e) {
        const layer = e.target;
        layer.setStyle({
          weight: 3,
          color: "#767676",
          fillColor: "#767676",
          dashArray: "",
          fillOpacity: 0.7,
        });
        layer.bringToFront();
      }

      function resetHighlight(e) {
        geojson.resetStyle(e.target);
      }

      // function zoomToFeature(e) {
      // 	map.fitBounds(e.target.getBounds());
      // }

      function onEachFeature(feature, layer) {
        layer.on({
          mouseover: highlightFeature,
          mouseout: resetHighlight,
          // click: zoomToFeature
        });
      }

      // 广东边界GeoJSON图层
      const geojson = L.geoJSON(regionStylesData, {
        style: {
          fillColor: "none",
          fillOpacity: 0,
          color: "black",
          weight: 1,
        },
        onEachFeature,
      }).addTo(mymap);

      //色标控件
      const legend = L.control({ position: "bottomright" });
      legend.onAdd = function (map) {
        const div = L.DomUtil.create("div", "legend");
        const grades = ["实况", "广州预报", "北京预报", "欧洲", "GD-9km"];
        const colors = [];
        const labels = [];
        for (let i = 0; i < grades.length; i++) {
          let from = grades[i];
          colors.push(
            `<i style="background: ${COLOR[i]};width: 12px; margin-left:19px; height: 12px; float: left; opacity: 0.76; margin-right: 19px"></i>`
          );
          labels.push(
            `<i style="width: 50px; height: 18px; text-align: center; float: left; font-style: normal;">${from}</i>`
          );
        }
        div.innerHTML = `<div style="background-color: white; width: 270px; height: 42px; padding:5px">
                   ${colors.join("") + "<br>" + labels.join("")}</div>`;
        return div;
      };
      legend.addTo(mymap);

      return mymap;
    }

    async function updateMap() {
      // 清除之前添加的所有标记图层
      markerLayer.clearLayers();

      // const jsonArray = typhoon;
      const jsonArray = await gettyphoonData(params);
      console.log(jsonArray);
      if (jsonArray === null) {
        showTopMessage("当前时间没有相关数据", 2000);
      } else {
        const dataSources = {
          shikuang: jsonArray["实况"],
          guangzhou: jsonArray["广州预报"],
          beijing: jsonArray["北京预报"],
          ouzhou: jsonArray["欧洲"],
          gd9km: jsonArray["GD-9km"],
        };
        const infoArrays = {};
        const coordinateArrays = {};

        for (const [key, dataSource] of Object.entries(dataSources)) {
          infoArrays[key] = dataSource.map((item) => {
            const ddatetime = new Date(item.ddatetime);
            const leadtime = item.leadtime || 0;
            const date = new Date(
              ddatetime.getTime() + leadtime * 60 * 60 * 1000
            ); // 将 leadtime 转换为毫秒并加到 ddatetime 上
            return {
              windSpeed: item.windspeed,
              pressure: item.pressure,
              date: date.toISOString().slice(0, -5) + "Z", // 将修改后的日期转换为字符串
            };
          });
          coordinateArrays[key] = dataSource.map((item) => [
            item.latitude,
            item.longitude,
          ]);
          const infoArray = infoArrays[key];
          const coordinates = coordinateArrays[key];
          const color = getColorForDataSource(key);
          //连接每个数据源的点
          const polyline = L.polyline(coordinates, { color: "#7d6353" });
          markerLayer.addLayer(polyline);
          // 连接实况数据的第一个点与其他四个数据源的第一个点
          if (key !== "shikuang" && coordinates.length > 0) {
            const firstCoordShikuang = coordinateArrays["shikuang"][0];
            const firstCoord = coordinates[0];
            const polylinecoo = L.polyline([firstCoordShikuang, firstCoord], {
              color: "#7d6353",
            });
            markerLayer.addLayer(polylinecoo);
          }
          //绘制数据源圆形标记并设置悬浮提示
          coordinates.forEach((coord, index) => {
            const circleMarker = L.circleMarker(coord, {
              radius: 5,
              color: color,
              fillOpacity: 1,
              fillColor: color,
            });
            markerLayer.addLayer(circleMarker);
            circleMarker.on("mouseover", function (e) {
              const info = infoArray[index];
              const content = `
            Coordinates: ${coord.toString()}<br>
           Wind Speed: ${info.windSpeed}<br>
           Pressure: ${info.pressure}<br>
            Date: ${info.date}
           `;
              this.bindPopup(content).openPopup();
            });
            circleMarker.on("mouseout", function (e) {
              this.closePopup();
            });
          });
        }

        function getColorForDataSource(dataSource) {
          switch (dataSource) {
            case "shikuang":
              return COLOR[0];
            case "guangzhou":
              return COLOR[1];
            case "beijing":
              return COLOR[2];
            case "ouzhou":
              return COLOR[3];
            case "gd9km":
              return COLOR[4];
            default:
              return "black";
          }
        }

        markerLayer.addTo(mymap);
      }
    }

    async function fetchData(params) {
      try {
        const Data = await gettyphoonData(params); // 使用接口文件中的函数获取数据
        return Data;
      } catch (error) {
        console.error("Error fetching data:", error);
        return null;
      }
    }

    function showTopMessage(message, duration) {
      // 创建一个提示元素
      const messageElement = document.createElement("div");
      messageElement.className = "top-message";
      messageElement.textContent = message;

      // 将提示元素添加到页面的顶部
      document.body.appendChild(messageElement);

      // 设置定时器，在一定时间后自动隐藏提示
      setTimeout(() => {
        messageElement.style.opacity = "0"; // 渐变消失
        setTimeout(() => {
          document.body.removeChild(messageElement); // 删除提示元素
        }, 1000); // 在渐变结束后删除元素
      }, duration);

      // 自定义样式
      messageElement.style.position = "fixed";
      messageElement.style.top = "100px";
      messageElement.style.left = "42%";
      messageElement.style.width = "300px";
      messageElement.style.borderRadius = "4px";
      messageElement.style.backgroundColor = "#88bffa";
      messageElement.style.color = "#fff";
      messageElement.style.padding = "10px 0";
      messageElement.style.textAlign = "center";
      messageElement.style.transition = "opacity 1s ease-in-out";
    }

    return {
      totalData,
    };
  },
};
</script>

<style scoped lang="scss">
.time-picker-fixed {
  position: fixed;
  top: 90%; /* 垂直居中 */
  left: 50%; /* 水平居中 */
  transform: translate(-50%, -50%); /* 居中偏移 */
  width: 1200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border-radius: 8px;
  background-color: transparent;
}

.time-picker {
  justify-content: center;
  width: 400px;
  display: flex;
  flex-direction: row; /* 水平布局 */
  align-items: center;
  border: 3px solid #007bff;
  padding: 20px;
  border-radius: 8px;
  background-color: #f0f0f0;
}

.head-name {
  color: #b0e3ff;
  font-weight: bold;
  font-size: xx-large;
  padding: 50px;
}

.box {
  display: flex;
  justify-content: center;
  align-items: center;
}

@media screen and (min-width: 700px) {
  .map {
    border: 3px double #c7e8ff;
    background-color: #6c8fff;
    margin: 60px;
    width: 70%;
    height: 65vh;

    #map {
      width: 100%;
      height: 65vh;
    }
  }
}

.custom-input {
  padding: 8px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 10px;
}

.custom-button {
  padding: 10px 20px;
  font-size: 16px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.custom-button:hover {
  background-color: #0056b3;
}
</style>
